package com.spring.lesson001.demo8;

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author vhans
 */
public class PrimaryTest {

    @Test
    public void normalBean() {
        String beanXml = "normalBean0018.xml";
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(beanXml);
        // 报错：有两个bean（Service1,Service2)实现了IService接口,spring容器无法选出合适的IService类型的bean
        System.out.println(context.getBean(NormalBean.IService.class));
    }

    @Test
    public void setterBean() {
        String beanXml = "setterBean0018.xml";
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(beanXml);
        // 按照类型通过setter的方式也无法选择子类Service
        System.out.println(context.getBean(SetterBean.class));
    }

    @Test
    public void primaryBean() {
        String beanXml = "primaryBean0018.xml";
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(beanXml);
        // 主要候选者为Service2
        System.out.println(context.getBean(PrimaryBean.IService.class));
        System.out.println(context.getBean(PrimaryBean.class));
    }

    @Test
    public void autowireCandidate() {
        String beanXml = "autowire-candidate0018.xml";
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(beanXml);
        // 1.按照IService类型查找所有符合条件的bean列表，此时容器中会返回满足IService这种类型并且autowire-candidate="true"的bean。
        // 2.1不满足，此时会再去看这个列表中是否只有一个主要的bean(即bean元素的primary="ture""的bean)。
        System.out.println(context.getBean(PrimaryBean.IService.class));
        System.out.println(context.getBean(PrimaryBean.class));
    }
}
